﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WAD.Model;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;

namespace WAD.DAL
{
    /// <summary>
    /// 广告数据库操作类
    /// </summary>
    public class DaoUrlSource : DAO
    {
        /// <summary>
        /// 添加一条记录
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static int Add(MUrlSource m)
        {
            String sql = "insert into url_source(md5,url,title,urlimg,[source],return_url)values(@md5,@url,@title,@urlimg,@source,@return_url);select @@identity";
            Database db = GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@md5", DbType.String, m.md5);
            db.AddInParameter(cmd, "@url", DbType.String, m.url);
            db.AddInParameter(cmd, "@title", DbType.String, m.title);
            db.AddInParameter(cmd, "@urlimg", DbType.String, m.urlimg);
            db.AddInParameter(cmd, "@source", DbType.String, m.source);
            db.AddInParameter(cmd, "@return_url", DbType.String, m.return_url);
            object obj = db.ExecuteScalar(cmd);
            return Int32.Parse(obj.ToString());
        }

        /// <summary>
        /// 通过id获取源码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static String GetHtml(String md5)
        {
            String sql = "select source from url_source where md5 = '" + md5 + "'";
            object html = ExecuteScalar(sql);
            return html == null ? null : (String)html;
        }

        public static Dictionary<string, object> GetHtml(String md5, bool isReturnId)
        {
            return DAO.Get("url_source", "md5='" + md5 + "'", "id,url,source,return_url");
        }

        public static Dictionary<string, object> GetHtml(String md5, bool isReturnId, string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl))
                return DAO.Get("url_source", "md5='" + md5 + "'", "id,url,source,return_url");
            else
                return DAO.Get("url_source", string.Format("md5='{0}' or return_url='{1}'", md5, returnUrl), "id,url,source,return_url");
        }
        /// <summary>
        /// 通过id获取源码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static String GetEntityById(int id)
        {
            String sql = "select source from url_source where id = " + id;
            return ExecuteScalar(sql).ToString();
        }

        public static Dictionary<string, object> GetEntityById(int id, string fields)
        {
            return Get("url_source", "id=" + id, fields);
        }
    }
}
